//
//  EpointAppDelegate.m
//  EpointFrame5
//
//  Created by 李亚春 on 13-12-4.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "EpointAppDelegate.h"
#import "EpointLoginViewController.h"
#import "EpointFrameDB.h"
#import "RIButtonItem.h"
#import "UIAlertView+Blocks.h"
#import "EpointPlaySound.h"
#import "EpointNavForPadViewController.h"
#import "EpointNavigationViewController.h"
#import "APIKey.h"
#import "Mail_Send_Task.h"
#import "TKAlertCenter.h"

//传统主界面
#import "WMH_Main_Static_ViewController.h"
#import "WMH_Main_ViewController.h"
//动态主界面：根据中间平台配置
#import "WMH_Main_Dynamic_ViewController.h"

//配置主界面
//0:九宫格（固定模块）
//1:动态模块（根据中间平台配置）
//2:上海虹口主界面（支持首页左右滑动）
//3:九宫格（固定模块）+ 左滑动菜单
//4:tab导航（navi+tabbar）
//5:默认主界面（固定模块+动态配置）
#define MainViewIndex 5

//滑动主界面
#import "LeftMenu_ViewController.h"
#import "RightMenu_ViewController.h"
#import "WMH_Main_SlideMenu_ViewController.h"
#import "SlideNavigationController.h"
#import "SHHK_Main_ViewController.h" //上海虹口主界面

//tab主界面
#import "WMH_MainTab1_ViewController.h"
#import "WMH_MainTab2_ViewController.h"
#import "WMH_MainTab3_ViewController.h"
#import "WMH_MainTab4_ViewController.h"

#import "URLTest_ViewController.h"

@interface EpointAppDelegate()
{
    int times;
}
@property (nonatomic, strong) PSStackedViewController *stackController;
@end

@implementation EpointAppDelegate
@synthesize stackController = stackController_;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    times = 10;
    XAppDelegate.clickItemPos=-1;
    //系统未捕获捕获异常处理
    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
    
    //初始化数据库
    [[EpointFrameDB alloc]init];
    
    //注册消息推送
    //    [self requestPushInfo];
    
    //添加网络变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:kReachabilityChangedNotification object:nil];
    
    self.res= [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    [self.res startNotifier];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    

    
    /*********************滑动主界面*********************/
    //左滑菜单
    LeftMenu_ViewController *leftview   = [[LeftMenu_ViewController alloc]init];
    //右滑菜单
    RightMenu_ViewController *rightview = [[RightMenu_ViewController alloc]init];
    //主界面
    WMH_Main_SlideMenu_ViewController *homeview       = [[WMH_Main_SlideMenu_ViewController alloc]init];
    //上海虹口主界面
    SHHK_Main_ViewController *shhk_mainview       = [[SHHK_Main_ViewController alloc]init];
    
    SlideNavigationController *slidenav;
    if(MainViewIndex == 2){
        slidenav = [[SlideNavigationController alloc] initWithRootViewController:shhk_mainview];
    }else if(MainViewIndex == 3){
        slidenav = [[SlideNavigationController alloc] initWithRootViewController:homeview];
    }
    
    [SlideNavigationController sharedInstance].rightMenu = rightview;
    [SlideNavigationController sharedInstance].leftMenu = leftview;
    
    // 定义右菜单 点击按钮
    UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [button setImage:[UIImage imageNamed:@"img_wmh_main_slidemenu_right_search"] forState:UIControlStateNormal];
    [button addTarget:[SlideNavigationController sharedInstance]
               action:@selector(toggleRightMenu)
     forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [SlideNavigationController sharedInstance].rightBarButtonItem = rightBarButtonItem;
    /*********************滑动主界面*********************/
    

    //动态配置主界面
    switch (MainViewIndex) {
            
        //0:九宫格（固定模块）
        case 0:
        {
            WMH_Main_Static_ViewController *view = [[WMH_Main_Static_ViewController alloc]init];
            EpointNavigationViewController *uv0 = [[EpointNavigationViewController alloc]initWithRootViewController:view:YES];
            self.window.rootViewController = uv0;
        }
           
            break;
        //1:动态模块（根据中间平台配置）
        case 1:
        {
            WMH_Main_Dynamic_ViewController *view = [[WMH_Main_Dynamic_ViewController alloc]init];
            EpointNavigationViewController *uv1 = [[EpointNavigationViewController alloc]initWithRootViewController:view:YES];
            self.window.rootViewController = uv1;
        }
            break;
        //2:上海虹口主界面（支持首页左右滑动）
        case 2:
            self.window.rootViewController = slidenav;
            break;
        //3:九宫格（固定模块）+ 左滑动菜单
        case 3:
            self.window.rootViewController = slidenav;
            break;
        //4:tab导航（navi+tabbar）
        case 4:
        {
            
            UITabBarController *tabview = [[UITabBarController alloc]init];
            //设置tab的标题
            tabview.title = @"新点微门户V5";
            
            WMH_MainTab1_ViewController *tab1view = [[WMH_MainTab1_ViewController alloc]init];
            tab1view.tabBarItem.title = @"主页";
            tab1view.tabBarItem.image = [UIImage imageNamed:@"img_wmh_maintab1"];
            
            WMH_MainTab2_ViewController *tab2view = [[WMH_MainTab2_ViewController alloc]init];
            tab2view.tabBarItem.title = @"新闻";
            tab2view.tabBarItem.image = [UIImage imageNamed:@"img_wmh_maintab2"];
            tab2view.view.backgroundColor = [UIColor blueColor];
            
            WMH_MainTab3_ViewController *tab3view = [[WMH_MainTab3_ViewController alloc]init];
            tab3view.tabBarItem.title = @"视频";
            tab3view.tabBarItem.image = [UIImage imageNamed:@"img_wmh_maintab3"];
            tab3view.view.backgroundColor = [UIColor blueColor];
            
            WMH_MainTab4_ViewController *tab4view = [[WMH_MainTab4_ViewController alloc]init];
            tab4view.tabBarItem.title = @"关于";
            tab4view.tabBarItem.image = [UIImage imageNamed:@"img_wmh_maintab4"];
            
            tabview.viewControllers = @[tab1view,tab2view,tab3view,tab4view];
            
            EpointNavigationViewController *uv0 = [[EpointNavigationViewController alloc]initWithRootViewController:tabview:YES];
            self.window.rootViewController = uv0;
            
        }
            break;
        //5:默认主界面（固定模块）
        case 5:
        {
            URLTest_ViewController *view5 = [[URLTest_ViewController alloc]init];
            EpointNavigationViewController *uv1 = [[EpointNavigationViewController alloc]initWithRootViewController:view5:YES];
            self.window.rootViewController = uv1;
        }
            break;
        default:
            break;
    }
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    if (!ISIOS7) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    [self addFolder];
    
    [self initTimer];
    
    //微门户：初始化设置参数
    [DBFrameService setConfigValue:WMH_InfoList_Date_FontSize   value:@"16"];           //新闻列表日期字体大小
    [DBFrameService setConfigValue:WMH_InfoList_Title_FontSize  value:@"17"];           //新闻列表标题字体大小
    [DBFrameService setConfigValue:WMH_NewsContent_FontSize     value:wmh_font_middle]; //新闻详情字体大小
    [DBFrameService setConfigValue:WMH_InfoList_Title_Length    value:@"30"];           //新闻列表标题长度
    
    return YES;
}



//申请注册消息推送
-(void)requestPushInfo
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
}

-(void)initPPSView{
    _leftWidth=PAD_LEFT_NAV_WIDTH_CONST;
    EpointNavForPadViewController *mainView = [[EpointNavForPadViewController alloc]initWithNibName:@"EpointNavForPadViewController" bundle:nil];
    self.stackController = [[PSStackedViewController alloc] initWithRootViewController:mainView];
    XAppDelegate.stackController.isMailCtrl=YES;
    [XAppDelegate.stackController setLargeLeftInset:PAD_LEFT_NAV_WIDTH];
    [XAppDelegate.stackController setLeftInset:PAD_LEFT_NAV_WIDTH];
    [XAppDelegate.stackController setStackWidth:AppWidth-PAD_LEFT_NAV_WIDTH];
    
    [XAppDelegate.stackController setDefaultShadowWidth:0];
    [XAppDelegate.stackController setDefaultShadowAlpha:0];
    
}
-(float)getLeftWidth{
    return _leftWidth;
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [[TKAlertCenter defaultCenter]postAlertWithMessage:[NSString stringWithFormat:@"%@",url]];
    return YES;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSString *tokeStr = [NSString stringWithFormat:@"%@",deviceToken];
    if ([tokeStr length] != 0) {
        tokeStr =[tokeStr stringByReplacingOccurrencesOfString:@"<" withString:@""];
        tokeStr =[tokeStr stringByReplacingOccurrencesOfString:@">" withString:@""];
        tokeStr =[tokeStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        [DBFrameService setConfigValue:Epoint_User_DevicePushToken value:tokeStr];
        NSLog(@"消息推送token:%@",tokeStr);
    }
}

- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    NSLog(@"Failed to get token, error: %@", error);
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"didReceiveRemoteNotification");
}

-(void)initTimer
{
    //时间间隔
    NSTimeInterval timeInterval =0;
    //定时器
    NSTimer  *showTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                                           target:self
                                                         selector:@selector(handleTimer)
                                                         userInfo:nil
                                                          repeats:NO];
    [[NSRunLoop currentRunLoop]addTimer:showTimer forMode:NSDefaultRunLoopMode];
}

-(void)handleTimer
{
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"update" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i",times] forKey:@"tips"]];
}

-(void)addFolder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *dirPath = [NSString stringWithFormat:@"%@/Documents/cache/",NSHomeDirectory()];
    [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
}

//当网络发生变化的时候，都会触发这个事件
-(void)change:(NSNotificationCenter *)notify{
    switch ([self.res currentReachabilityStatus]) {
        case NotReachable:
            self.netWorkStatus = 1;
            NSLog(@"NO NETWORK");
            break;
        case ReachableViaWiFi:
            self.netWorkStatus = 1;
            NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:{
            self.netWorkStatus = 1;
            NSLog(@"3G");
        }
            break;
        default:
            break;
    }
}


void UncaughtExceptionHandler(NSException *exception) {
    NSLog(@"UncaughtExceptionHandler");
    NSString *key = [NSString stringWithFormat:@"ERROR%@",[EpointDateUtils getCurrentDateStr:@"YYYYMMddHHmmss"]];
    NSArray *arr = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSString *userguid = [DBFrameService getUserGuid];
    NSString *errorLog = [NSString stringWithFormat:@"<user>%@</user><name>%@</name><reason>%@</reason><errorlog>%@</errorlog>",userguid,name,reason,arr];
    NSLog(@"errorLog=%@",errorLog);
    [DBFrameService setCacheValue:key value:errorLog];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    NSLog(@"applicationWillResignActive");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSLog(@"applicationDidEnterBackground");
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    NSLog(@"applicationWillEnterForeground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    NSLog(@"applicationDidBecomeActive");
    application.applicationIconBadgeNumber = 0;
    
    //这里获取用户数据
    //[NSThread detachNewThreadSelector:@selector(getUserInfoNums) toTarget:self withObject:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"applicationWillTerminate");
}

#pragma mark 点聚修复xcode6编译不过的问题#################################################
FILE *fopen$UNIX2003( const char *filename, const char *mode )

{
    return fopen(filename, mode);
}

size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )

{
    return fwrite(a, b, c, d);
}


#pragma mark 点聚修复xcode6编译不过的问题#################################################

@end
